package com.huluobo.a2207parkdemo.news

import androidx.lifecycle.MutableLiveData
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import com.huluobo.base.bean.NewsBeanItem
import com.huluobo.base.mvvm.BaseViewModel
import com.huluobo.base.net.ApiService
import com.huluobo.base.net.getService
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import okhttp3.RequestBody
import javax.inject.Inject

/**
 *  Created by LC on 2024/11/23.
 */
@HiltViewModel
class NewsViewModel @Inject constructor(
    val apiService: ApiService
) : BaseViewModel() {
    val getAllNewsSuccess by lazy { MutableLiveData<String>() }
    fun getAllNews(body: RequestBody) {
        executeNetwork(
            { apiService.getAllNews(body) },
            getAllNewsSuccess::postValue
        )
    }

    val addNewsSuccess by lazy { MutableLiveData<String>() }
    fun addNews(body: RequestBody) {
        executeNetwork(
            { apiService.addNews(body) },
            addNewsSuccess::postValue
        )
    }

    fun getNewsPagingData(): Flow<PagingData<NewsBeanItem>> {
        return Repo.getNewsPagingData()
    }
}

object Repo {
    private const val PAGE_SIZE = 5
    private val apiService = getService<ApiService>()

    fun getNewsPagingData(): Flow<PagingData<NewsBeanItem>> {
        return Pager(
            config = PagingConfig(pageSize = PAGE_SIZE, prefetchDistance = PAGE_SIZE * 5),
            pagingSourceFactory = { NewsPagingSource(apiService) }
        ).flow
    }
}